package com.dhcc.sds.busi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.RedisUtil;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.*;
import com.dhcc.sds.busi.vo.AnalysisSdsPortalVo;
import com.dhcc.sds.busi.vo.SdsOPQcincaseVo;
import com.dhcc.sds.task.QcTask;
import com.dhcc.sds.util.StrUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhangdc
 * @version 1.0
 * @date 2022/5/12 14:54
 */
@Service
public class SdsOPQcincaseServiceImpl implements ISdsOPQcincaseService {

    @Autowired
    private ICdcEpisodeService cdcEpisodeService;
    @Autowired
    private ISdsQcincaseService sdsQcincaseService;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Autowired
    private ISdsQcincaseOperlogService sdsQcincaseOperlogService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ISdsQcfitemExecresultService sdsQcfitemExecresultService;
    @Autowired
    private ISdsQcFormShowService sdsQcFormShowService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<SdsOPQcincaseVo> selectQCOPMrListByDate(Map<String, Object> params) {
        List<SdsOPQcincaseVo> res = new ArrayList<>();
        String dateType = (String) params.get("aDateType");
        String status = "";
        List<String> statusList = new ArrayList<>();
        if (!StringUtils.isEmpty(params.get("aStatus"))){
            status = (String) params.get("aStatus");
            String[] split = status.split(",");
            statusList = Arrays.asList(split);
            params.put("statusList", statusList);
        }
        //就诊类型:门诊
        CdcDictionaryEntity admType = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "O");
        //就诊状态:取消
        CdcDictionaryEntity admStatus = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_status", "C");
        params.put("busAdmTypeId", admType.getId());
        params.put("busAdmStatusId", admStatus.getId());
        if (!StringUtils.isEmpty(params.get("aRegNo"))){
            //按登记号查询
            String regNo = (String) params.get("aRegNo");
            //todo 补全登记号 m里面RegNoCon方法
            List<CdcEpisodeEntity> cdcEpisodeEntities = cdcEpisodeService.selectList(new EntityWrapper<CdcEpisodeEntity>()
                    .eq("regist_num", regNo)
                    .eq("bus_adm_type_id", admType.getId())
                    .ne("bus_adm_status_id", admStatus.getId()));
            if (cdcEpisodeEntities.isEmpty()){
                //session失效时间
                redisUtil.set("gridQCMrList", res, 1800);
                return res;
            }else {
                //判断是否入单病种
                List<Long> incaseIds = new ArrayList<>();
                for (CdcEpisodeEntity cdcEpisodeEntity : cdcEpisodeEntities){
                    SdsQcincaseEntity sdsQcincaseEntity = sdsQcincaseService.selectOne(new EntityWrapper<SdsQcincaseEntity>()
                            .eq("episode_id", cdcEpisodeEntity.getId()));
                    if (StringUtils.isEmpty(sdsQcincaseEntity)){
                        SdsOPQcincaseVo sdsOPQcincaseVo = new SdsOPQcincaseVo();
                        BeanUtils.copyProperties(cdcEpisodeEntity, sdsOPQcincaseVo);
                        res.add(sdsOPQcincaseVo);
                    }else {
                        incaseIds.add(sdsQcincaseEntity.getId());
                    }
                }
                List <SdsOPQcincaseVo> sdsOPQcincaseVoList = new ArrayList<>();
                if (!incaseIds.isEmpty()){
                    sdsOPQcincaseVoList = sdsQcincaseService.selectOPIncaseByRegNo(incaseIds);
                    for (SdsOPQcincaseVo sdsOPQcincaseVo : sdsOPQcincaseVoList){
                        String excludeInfo = sdsQcincaseOperlogService.getInGroupOrOutOperReason(sdsOPQcincaseVo.getRowId(), sdsOPQcincaseVo.getQcCurrStatus());
                        sdsOPQcincaseVo.setExcludeInfo(excludeInfo);
                    }
                }
                res.addAll(sdsOPQcincaseVoList);
            }
            redisUtil.set("gridQCMrList", res, 1800);
            return res;
        }else {
            //按日期查询
            //上报日期
            if (Objects.equals("UpQC", dateType)){
                if (status.contains("Up") || StringUtils.isEmpty(status)){
                    res = sdsQcincaseOperlogService.selectOPIncaseByCondition(params);
                }else {
                    //上报日期状态不为上报状态
                    res = null;
                }
            }else {
                res = sdsQcincaseService.selectOPIncaseByCondition(params);
            }
            redisUtil.set("gridQCMrList", res, 1800);
            return res;
        }
    }

    @Override
    public String selectRulesByQcEntityId(Map<String, Object> params) {
        String res = "";
        String qcEntityId = (String) params.get("qcEntityId");
        Long entityId = Long.parseLong(qcEntityId);
        String ruleType = (String) params.get("ruleType");
        List<SdsQcentityRuleEntity> sdsQcentityRuleEntities = sdsQcentityRuleService.selectList(new EntityWrapper<SdsQcentityRuleEntity>()
                .eq("entity_id", entityId)
                .eq("rule_type", ruleType).eq("is_active",1).eq("is_only",0));
        for (SdsQcentityRuleEntity sdsQcentityRuleEntity : sdsQcentityRuleEntities){
            sdsQcentityRuleEntity.getId();
            sdsQcentityRuleEntity.getRuleDesc();
            res += sdsQcentityRuleEntity.getId() + "," + sdsQcentityRuleEntity.getRuleDesc() + ";";
        }
        if (!StringUtils.isEmpty(res)){
            res = res.substring(0, res.length() - 1);
        }
        return res;
    }

    @Override
    public JSONArray selectQcEntityByLocId(Long aLocOId) {
        //todo 过滤aLocOId
        //return sdsQcentityService.selectList(null);
        return sdsQcentityService.getEntityMapByConfig("SDS", "SDOPQCEntity");
    }

    @Override
    public int inQcEntity(Map<String, Object> params) {
        int res = 0;
        String episodeId = (String) params.get("episodeId");
        CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeService.selectById(Long.parseLong(episodeId));
        String qcDicId = (String) params.get("qcDicId");
        /*String inUserId = (String) params.get("inUserId");
        String inLocId = (String) params.get("inLocId");*/
        String ruleStr = (String) params.get("ruleStr");
        String resume = (String) params.get("resume");
        String execUser = (String) params.get("execUser");
        SdsQcincaseEntity entityByEpisodeId = sdsQcincaseService.selectEntityByEpisodeId(Long.parseLong(episodeId));
        SdsQcincaseEntity sdsQcincaseEntity = new SdsQcincaseEntity();
        sdsQcincaseEntity.setEpisodeId(Long.parseLong(episodeId));
        sdsQcincaseEntity.setEntityId(Long.parseLong(qcDicId));
        sdsQcincaseEntity.setInUserId(cdcEpisodeEntity.getAdmDoctorId());
        sdsQcincaseEntity.setInLocId(cdcEpisodeEntity.getAdmLocId());
        sdsQcincaseEntity.setInWardId(cdcEpisodeEntity.getAdmWardId());
        sdsQcincaseEntity.setInDate(new Date());
        sdsQcincaseEntity.setInTime(new Date());
        sdsQcincaseEntity.setState("I");
        sdsQcincaseEntity.setGroupStatus("ActivePart");
        sdsQcincaseEntity.setFillingStatus("NotFilled");
        sdsQcincaseEntity.setReportStatus("NotUp");
        boolean change;
        if (CommonUtil.isNotEmpty(entityByEpisodeId)&&entityByEpisodeId.getState().equals("P")){
            sdsQcincaseEntity.setId(entityByEpisodeId.getId());
            change = sdsQcincaseService.updateById(sdsQcincaseEntity);
        }else {
            if ("I".equals(sdsQcincaseEntity.getState())) {
                Wrapper<SdsQcincaseEntity> wrapper = new EntityWrapper<>();
                wrapper.eq("episode_id", sdsQcincaseEntity.getEpisodeId())
                        .eq("entity_id", sdsQcincaseEntity.getEntityId())
                        .eq("in_user_id", sdsQcincaseEntity.getInUserId())
                        .eq("in_loc_id", sdsQcincaseEntity.getInLocId())
                        .eq("in_ward_id", sdsQcincaseEntity.getInWardId())
                        .eq("state", sdsQcincaseEntity.getState())
                        .eq("group_status", sdsQcincaseEntity.getGroupStatus())
                        .eq("filling_status", sdsQcincaseEntity.getFillingStatus())
                        .eq("report_status", sdsQcincaseEntity.getReportStatus());
                SdsQcincaseEntity qcincaseEntity = sdsQcincaseService.selectOne(wrapper);
                if (qcincaseEntity != null) {
                    return 0;
                }
            }
            change = sdsQcincaseService.insert(sdsQcincaseEntity);
        }
        if (change){
            //增加病历状态记录
            SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity = new SdsQcincaseOperlogEntity();
            sdsQcincaseOperlogEntity.setInCaseId(sdsQcincaseEntity.getId());
            sdsQcincaseOperlogEntity.setOperState("I");
            sdsQcincaseOperlogEntity.setOperUser(execUser);
            sdsQcincaseOperlogEntity.setOperDate(new Date());
            sdsQcincaseOperlogEntity.setOperReason(ruleStr);
            sdsQcincaseOperlogEntity.setOperResume(resume);
            boolean insert1 = sdsQcincaseOperlogService.insert(sdsQcincaseOperlogEntity);
            if (insert1){
                res = 1;
            }
            //执行自动取值
            sdsQcfitemExecresultService.execItemResult(sdsQcincaseEntity.getId());
            //表单填充率
            try {
                sdsQcFormShowService.getItemResult(sdsQcincaseEntity.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    @Override
    public List<SdsQcincaseOperlogEntity> selectOperLogByIncaseId(Long incaseId) {
        List<SdsQcincaseOperlogEntity> sdsQcincaseOperlogEntities = sdsQcincaseOperlogService.selectList(new EntityWrapper<SdsQcincaseOperlogEntity>()
                .eq("in_case_id", incaseId));
        for (SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity : sdsQcincaseOperlogEntities){
            sdsQcincaseOperlogEntity.setOperState( sdsCommonService.getDictDesc("SDQCMrStatus", sdsQcincaseOperlogEntity.getOperState()));
        }
        return sdsQcincaseOperlogEntities;
    }

}
